#include "mywidget.h"
#include "ui_mywidget.h"

myWidget::myWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::myWidget)
{
    ui->setupUi(this);
    tcp1=new QTcpServer(this);
    tcp2=new QTcpServer(this);
    sockfd1=new QTcpSocket(this);
    sockfd2=new QTcpSocket(this);
    if(tcp1->listen(QHostAddress::Any,6000)) qDebug()<<"tcp1 is listen!";
    if(tcp2->listen(QHostAddress::Any,6100)) qDebug()<<"tcp2 is listen!";
    connect(tcp1,SIGNAL(newConnection()),this,SLOT(tcp1accept()));
    connect(tcp2,SIGNAL(newConnection()),this,SLOT(tcp2accept()));
}
myWidget::~myWidget()
{
    delete ui;

}

void myWidget::tcp1accept()
{
    sockfd1=tcp1->nextPendingConnection();
    connect(sockfd1,SIGNAL(readyRead()),this,SLOT(Data()));
    qDebug()<<"tcp1 is accept!";
    tcp1->close();
}

void myWidget::tcp2accept()
{
    sockfd2=tcp2->nextPendingConnection();
    connect(sockfd2,SIGNAL(readyRead()),this,SLOT(Data()));
    qDebug()<<"tcp2 is accept!";
    tcp2->close();
}

void myWidget::Data(){
    qDebug()<<"Data to go!";
    buf=sockfd1->readAll();
    qDebug()<<"recv "<<buf.size();
    qDebug()<<sockfd2->write(buf);
    buf.clear();
}

void myWidget::on_reset_server_clicked()
{
    if(sockfd1->isOpen()) sockfd1->close();
    if(sockfd2->isOpen()) sockfd2->close();
    tcp1->close();
    tcp2->close();
    if(tcp1->listen(QHostAddress::Any,6000)) qDebug()<<"tcp1 is listen!";
    if(tcp2->listen(QHostAddress::Any,6100)) qDebug()<<"tcp2 is listen!";
}
